package com.rp.common.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;

/**
 * RP平台JSON工具类
 * @author JMan
 *
 */
public class JsonUtil {
	
	public static final ObjectMapper mapper = new ObjectMapper();

	public static ObjectMapper getMapper() {
		return mapper;
	}

	public static JavaType getCollectionType(Class<?> collectionClass,
			Class<?>... elementClasses) {
		/*
		 * 添加下面这句可以解决报UnrecognizedPropertyException异常的问题，
		 * 目的是忽略掉一些实体类中没有的属性
		 */
		mapper.configure(
				DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		return mapper.getTypeFactory().constructParametricType(collectionClass,
				elementClasses);
	}
	
	/**
	 * JSON转Map
	 * @param jsonString
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> jsonToMap(String json) {
		Map<String, Object> map = null;
		try {
			map = mapper.readValue(json, Map.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;
	}
	
	/**  
     * JSON转实体类
     * @param json
     * @param className  
     * @return  
     */
    @SuppressWarnings("unchecked")
    public static <T> T jsonToBean(String json, Class<T> className) {
        JSONObject jsonObject = JSONObject.fromObject(json);
        T bean = (T) JSONObject.toBean(jsonObject, className); 
        
        return bean;
    }
	
	/**
	 * JSON转实体类List
	 * @param json Json数据串
	 * @param className 对应实体类的全路径类名
	 * @return
	 * @throws Exception 
	 */
	public static ArrayList jsonToList(String json, String className) throws Exception{
		try {
			return JsonUtil.getMapper().readValue(json, JsonUtil.getCollectionType(ArrayList.class, Class.forName(className)));
		} catch (JsonParseException e) {
			e.printStackTrace();
			throw new Exception("JSON转实体类List发生错误，异常类来自："+e.getClass().toString());
		} catch (JsonMappingException e) {
			e.printStackTrace();
			throw new Exception("JSON转实体类List发生错误，异常类来自："+e.getClass().toString());
		} catch (IOException e) {
			e.printStackTrace();
			throw new Exception("JSON转实体类List发生错误，异常类来自："+e.getClass().toString());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new Exception("JSON转实体类List发生错误，异常类来自："+e.getClass().toString());
		}
	}
	
	/**
	 * JSON转Map List
	 * @param json
	 * @return
	 */
    public static List<Map<String, Object>> jsonToList(String json){
        JSONArray jsonArr = JSONArray.fromObject(json);
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        Iterator<JSONObject> it = jsonArr.iterator();
        while(it.hasNext()){
            JSONObject json2 = it.next();
            list.add(jsonToMap(json2.toString()));
        }
        return list;
    }
	
	/*@SuppressWarnings({ "rawtypes", "unchecked" })
	public static ArrayList toList(List tree, String parentId, String childrenField, String idField, String parentIdField)
    {
    	ArrayList list = new ArrayList();
        for (int i = 0, len = tree.size(); i < len; i++)
        {
            Map task = (Map)tree.get(i);

            task.put(parentIdField, parentId);
            list.add(task);
        	
            List children = (List)task.get(childrenField);

            if (children != null && children.size() > 0)
            {
            	String id = task.get(idField) == null ?"" : task.get(idField).toString();
                List list2 = toList(children, id, childrenField, idField, parentIdField);
                list.addAll(list2);
            }
            //task.remove(childrenField);
        }
        return list;
    }*/
	

	/*@SuppressWarnings("rawtypes")
	public static Object decode(String json) {
		if (RpUtil.isNullOrEmpty(json))
			return "";
		JSONDeserializer deserializer = new JSONDeserializer();
		//deserializer.use(String.class, new DateTransformer(
		//		"yyyy-MM-dd'T'HH:mm:ss"));
		Object obj = deserializer.deserialize(json);
		if (obj != null && obj.getClass() == String.class) {
			return decode(obj.toString());
		}
		return obj;
	}*/

}
